'use client'

import { useState, useEffect } from 'react'
import { useRouter, useParams } from 'next/navigation'
import { ArrowLeft, Edit, Trash2, Eye, Calendar, User, Tag, Folder, BarChart3, Clock, CheckCircle, Archive, Star } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Separator } from '@/components/ui/separator'
import { knowledgeAPI } from '@/lib/api'
import { toast } from 'sonner'
import { KnowledgeBase } from '@/lib/types'
import { 
  CompactLayout, 
  CompactHeading, 
  CompactSubheading,
  CompactCard 
} from '@/components/ui/compact-layout'

export default function KnowledgeViewPage() {
  const router = useRouter()
  const params = useParams()
  const articleId = params.id as string
  
  const [article, setArticle] = useState<KnowledgeBase | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isSubmitting, setIsSubmitting] = useState(false)

  // 获取文章详情
  const fetchArticle = async () => {
    try {
      setIsLoading(true)
      const response = await knowledgeAPI.getKnowledgeBase(articleId)
      setArticle(response)
    } catch (error: any) {
      console.error('Failed to fetch article:', error)
      toast.error(error.message || '获取文章详情失败')
      router.push('/knowledge')
    } finally {
      setIsLoading(false)
    }
  }

  // 更新文章状态
  const updateArticleStatus = async (status: string) => {
    if (!article) return
    
    try {
      setIsSubmitting(true)
      await knowledgeAPI.updateKnowledgeBaseStatus(articleId, status)
      toast.success('文章状态更新成功')
      fetchArticle() // 重新获取文章详情
    } catch (error: any) {
      console.error('Failed to update article status:', error)
      toast.error(error.message || '更新文章状态失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 切换精选状态
  const toggleFeatured = async () => {
    if (!article) return
    
    try {
      setIsSubmitting(true)
      await knowledgeAPI.toggleFeatured(articleId, !article.featured)
      toast.success(article.featured ? '取消精选成功' : '设为精选成功')
      fetchArticle() // 重新获取文章详情
    } catch (error: any) {
      console.error('Failed to toggle featured status:', error)
      toast.error(error.message || '更新精选状态失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 删除文章
  const deleteArticle = async () => {
    if (!confirm('确定要删除这篇文章吗？此操作不可撤销。')) {
      return
    }

    try {
      setIsSubmitting(true)
      await knowledgeAPI.deleteKnowledgeBase(articleId)
      toast.success('文章删除成功')
      router.push('/knowledge')
    } catch (error: any) {
      console.error('Failed to delete article:', error)
      toast.error(error.message || '删除文章失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 获取状态徽章
  const getStatusBadge = (status: string) => {
    const statusConfig = {
      DRAFT: { label: '草稿', variant: 'secondary' as const, icon: Edit },
      PUBLISHED: { label: '已发布', variant: 'default' as const, icon: CheckCircle },
      ARCHIVED: { label: '已归档', variant: 'outline' as const, icon: Archive }
    }
    
    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.DRAFT
    const IconComponent = config.icon
    
    return (
      <Badge variant={config.variant} className="flex items-center space-x-1">
        <IconComponent className="h-3 w-3" />
        <span>{config.label}</span>
      </Badge>
    )
  }

  // 初始化加载
  useEffect(() => {
    if (articleId) {
      fetchArticle()
    }
  }, [articleId])

  if (isLoading) {
    return (
      <CompactLayout>
        <div className="flex items-center justify-center h-64">
          <div className="flex items-center space-x-2">
            <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
            <span>加载中...</span>
          </div>
        </div>
      </CompactLayout>
    )
  }

  if (!article) {
    return (
      <CompactLayout>
        <div className="text-center py-8">
          <p className="text-muted-foreground">文章不存在或已被删除</p>
          <Button onClick={() => router.push('/knowledge')} className="mt-4">
            返回文章列表
          </Button>
        </div>
      </CompactLayout>
    )
  }

  return (
    <CompactLayout>
      {/* 页面头部 */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center space-x-4">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => router.push('/knowledge')}
            className="h-8 w-8"
          >
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <CompactHeading>{article.title}</CompactHeading>
            <CompactSubheading>
              查看文章详情
            </CompactSubheading>
          </div>
        </div>
        
        <div className="flex items-center space-x-2">
          <Button
            variant="outline"
            onClick={() => router.push(`/knowledge/${articleId}/edit`)}
            className="flex items-center space-x-2"
          >
            <Edit className="h-4 w-4" />
            <span>编辑</span>
          </Button>
          <Button
            variant="outline"
            onClick={toggleFeatured}
            disabled={isSubmitting}
            className={article.featured ? "bg-yellow-50 border-yellow-200 text-yellow-700" : ""}
          >
            <Star className={`h-4 w-4 ${article.featured ? "fill-current" : ""}`} />
            <span>{article.featured ? '取消精选' : '设为精选'}</span>
          </Button>
          <Button
            variant="outline"
            onClick={() => updateArticleStatus(
              article.status === 'PUBLISHED' ? 'DRAFT' : 'PUBLISHED'
            )}
            disabled={isSubmitting}
          >
            <CheckCircle className="h-4 w-4" />
            <span>{article.status === 'PUBLISHED' ? '设为草稿' : '发布'}</span>
          </Button>
          <Button
            variant="destructive"
            onClick={deleteArticle}
            disabled={isSubmitting}
          >
            <Trash2 className="h-4 w-4" />
            <span>删除</span>
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
        {/* 主要内容 */}
        <div className="lg:col-span-3 space-y-6">
          {/* 文章内容 */}
          <CompactCard>
            <CardHeader>
              <CardTitle className="text-xl">{article.title}</CardTitle>
              {article.description && (
                <p className="text-muted-foreground">{article.description}</p>
              )}
            </CardHeader>
            <CardContent>
              <div className="max-w-none text-sm leading-relaxed">
                <div 
                  dangerouslySetInnerHTML={{ __html: article.content }} 
                  className="[&>h1]:text-2xl [&>h1]:font-bold [&>h1]:mb-4 [&>h1]:mt-6 [&>h2]:text-xl [&>h2]:font-semibold [&>h2]:mb-3 [&>h2]:mt-5 [&>h3]:text-lg [&>h3]:font-medium [&>h3]:mb-2 [&>h3]:mt-4 [&>p]:mb-3 [&>ul]:mb-3 [&>ol]:mb-3 [&>li]:mb-1 [&>code]:bg-muted [&>code]:px-1 [&>code]:py-0.5 [&>code]:rounded [&>pre]:bg-muted [&>pre]:p-3 [&>pre]:rounded-lg [&>pre]:overflow-x-auto [&>blockquote]:border-l-4 [&>blockquote]:border-border [&>blockquote]:pl-4 [&>blockquote]:italic [&>blockquote]:text-muted-foreground"
                />
              </div>
            </CardContent>
          </CompactCard>
        </div>

        {/* 侧边栏信息 */}
        <div className="space-y-6">
          {/* 文章状态 */}
          <CompactCard>
            <CardHeader>
              <CardTitle className="text-lg">文章状态</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">状态</span>
                {getStatusBadge(article.status)}
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">精选</span>
                <Badge variant={article.featured ? "default" : "outline"}>
                  {article.featured ? '是' : '否'}
                </Badge>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">浏览量</span>
                <span className="text-sm font-medium">{article.viewCount}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">点赞数</span>
                <span className="text-sm font-medium">{article.likeCount}</span>
              </div>
            </CardContent>
          </CompactCard>

          {/* 文章信息 */}
          <CompactCard>
            <CardHeader>
              <CardTitle className="text-lg">文章信息</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center space-x-2 text-sm">
                <User className="h-4 w-4 text-muted-foreground" />
                <span className="text-muted-foreground">作者:</span>
                <span className="font-medium">{article.author.username}</span>
              </div>
              
              {article.category && (
                <div className="flex items-center space-x-2 text-sm">
                  <Folder className="h-4 w-4 text-muted-foreground" />
                  <span className="text-muted-foreground">分类:</span>
                  <Badge variant="outline" className="text-xs">
                    {article.category.name}
                  </Badge>
                </div>
              )}
              
              {article.tags && article.tags.length > 0 && (
                <div className="space-y-2">
                  <div className="flex items-center space-x-2 text-sm">
                    <Tag className="h-4 w-4 text-muted-foreground" />
                    <span className="text-muted-foreground">标签:</span>
                  </div>
                  <div className="flex flex-wrap gap-1">
                    {article.tags.map((tag) => (
                      <Badge key={tag.id} variant="outline" className="text-xs">
                        {tag.name}
                      </Badge>
                    ))}
                  </div>
                </div>
              )}
              
              <Separator />
              
              <div className="space-y-2 text-sm">
                <div className="flex items-center space-x-2">
                  <Calendar className="h-4 w-4 text-muted-foreground" />
                  <span className="text-muted-foreground">创建时间:</span>
                  <span>{new Date(article.createdAt).toLocaleString()}</span>
                </div>
                {article.updatedAt && (
                  <div className="flex items-center space-x-2">
                    <Clock className="h-4 w-4 text-muted-foreground" />
                    <span className="text-muted-foreground">更新时间:</span>
                    <span>{new Date(article.updatedAt).toLocaleString()}</span>
                  </div>
                )}
                {article.publishedAt && (
                  <div className="flex items-center space-x-2">
                    <CheckCircle className="h-4 w-4 text-muted-foreground" />
                    <span className="text-muted-foreground">发布时间:</span>
                    <span>{new Date(article.publishedAt).toLocaleString()}</span>
                  </div>
                )}
              </div>
            </CardContent>
          </CompactCard>

          {/* 统计信息 */}
          <CompactCard>
            <CardHeader>
              <CardTitle className="text-lg">统计信息</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">总浏览量</span>
                <div className="flex items-center space-x-1">
                  <BarChart3 className="h-4 w-4 text-muted-foreground" />
                  <span className="font-medium">{article.viewCount}</span>
                </div>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">总点赞数</span>
                <div className="flex items-center space-x-1">
                  <Star className="h-4 w-4 text-muted-foreground" />
                  <span className="font-medium">{article.likeCount}</span>
                </div>
              </div>
            </CardContent>
          </CompactCard>
        </div>
      </div>
    </CompactLayout>
  )
}
